import struct
#import matplotlib.pyplot as plt

import numpy as np
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout

import sys

'''
agrvstr = sys.argv

if len(agrvstr) < 3:
    print('arg error, help: data_parse file_name channel_num')
    exit()

filename = agrvstr[1]

plot_ch = int(agrvstr[2])
'''
#filename="D:/Cnd_Driver/dataRaw/Rawdata_FPGA1_Frame"+"51"+".bin"
filename="D:/Project/pabone/data/raw/Rawdata_FPGA1_Frame5.bin"
filename="D:/Project/pabone/data/raw/Rawdata_FPGA1_Frame38.bin"


for plt_dis_num in range(1, 2):

    #plot_ch = plt_dis_num
    plot_ch = 1
    f = open(filename, 'rb')
    data = f.read(8)

    header = struct.unpack('3B5B', data)

    b1 = header[2]
    b2 = header[1]
    b3 = header[0]

    length = b1 + b2 * 256 + b3 * 256 * 256

    chs = []
    ch1 = []

    iter = int(length/16)

    print(header)

    print ("iter:",iter)
    print ("length:",length)
    print ("b1",b1)
    print ("b2",b2)
    print ("b3",b3)

    for line in range(0, iter):
        ch = []   # 所有通道一次采样的值
        for j in range(0, 16):
            data = f.read(8)
            chb = struct.unpack('8B', data)
            chb = chb[::-1]
            for i in range(0, 4):
                b1 = int(chb[i * 2])
                b2 = int(chb[i * 2 + 1])
                if b2 < int(128):
                    num = b1 + b2 * 256
                else:
                    num = b1 + b2 * 256 - 0x10000
                #if(num != 0 & num != -1):
                 #   print ("erro num=",num)
                ch.append(num)

        chs.append(ch)
        ch1.append(ch[plot_ch - 1])
    f.close()

    '''
    plt.figure(figsize=(40,5),dpi=100)
    plt.scatter(range(0, iter),ch1)
    plt.show()
    '''
    #plt.plot(range(0, iter), ch1,"ro")
    # plt.plot(range(0, iter), ch1)
    # plt.xlabel('Index')
    # ylabelstr = 'Channel' + str(plot_ch)
    # plt.ylabel(ylabelstr)
    # plt.grid(True)
    # plt.show()

    app = pg.mkQApp("Testing")
    win = pg.GraphicsLayoutWidget(show = True, title = "acq data")
    win.resize(1000,600)
    win.setWindowTitle('pyqtgraph example: Plotting')
    pg.setConfigOptions(antialias=True)

    p4 = win.addPlot(title="Parametric, grid enabled")
    x = np.array(range(0, iter))
    y = np.array(ch1)
    p4.plot(x, y)
    p4.showGrid(x=True, y=True)

if __name__ == '__main__':
    pg.exec()



